package com.wise.service.impl;

import com.wise.mapper.MsgLogMapper;
import com.wise.pojo.MsgConstants;
import com.wise.pojo.MsgLog;
import com.wise.pojo.Person;
import com.wise.mapper.PersonMapper;
import com.wise.service.IPersonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wise
 * @since 2021-09-22
 */
@Service
public class PersonServiceImpl extends ServiceImpl<PersonMapper, Person> implements IPersonService {
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MsgLogMapper msgLogMapper;

    @Override
    public String savePerson(Person person) {
        String res = "";
        if(1==personMapper.savePerson(person)){
            res= "================保存人员成功";
            //构造消息日志并插入数据库
            String msgId = UUID.randomUUID().toString();
            MsgLog msgLog = new MsgLog();
            msgLog.setMsgId(msgId);
            msgLog.setPid(person.getId());
            msgLog.setStatus(0);
            msgLog.setRouteKey(MsgConstants.MAIL_ROUTING_KEY_NAME);
            msgLog.setExchange(MsgConstants.MAIL_EXCHANGE_NAME);
            msgLog.setCount(0);
            //重试时间
            msgLog.setTryTime(LocalDateTime.now().plusMinutes(MsgConstants.MSG_TIMEOUT));
            msgLogMapper.insert(msgLog);

            //发送消息到rabbitmq  :交换机名称 路由键 消息 消息id
            rabbitTemplate.convertSendAndReceive(MsgConstants.MAIL_EXCHANGE_NAME,MsgConstants.MAIL_ROUTING_KEY_NAME,person,new CorrelationData(msgId));

        }else{
            res= "================保存人员失败";
        }
        return res;
    }
}
